package cn.pzhu.services.admin;

import cn.pzhu.model.Privilege;
import cn.pzhu.model.Role;
import cn.pzhu.model.User;
import cn.pzhu.services.BaseServices;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dongp on 2016/4/24.
 */
public class PrivilegeServices extends BaseServices{

    public boolean ajaxAdd(String privilegeID, String masterVal, String accessName, String accessVal) {

        // 检查是否重复
        Privilege privilege = Privilege.dao.findById(privilegeID);
        if(privilege != null) {
            return false;
        }

        // 保存
        Role role = Role.dao.findFirst("select * from role where roleValue = ? ", masterVal);
        String masterName = role.getStr("roleName");
        boolean result = new Privilege().set("masterName", masterName).set("masterVal", masterVal)
                .set("accessName", accessName).set("accessVal",accessVal).save();

        return result;
    }

    public List ajaxQuery(String pageNumber, String pageSize, String search) {
        ArrayList arrts = new ArrayList();
        Map<String,Object> map = new HashMap<>();

        List<Privilege> privileges = Privilege.dao.find("select * from privilege p where p.masterName like '%"
                + search + "%' limit " + pageNumber + "," + pageSize);
        arrts.add(privileges);

        Privilege user = Privilege.dao.findFirst("select count(*) total from privilege p where p.masterName like '%"+search+"%'");
        Long total = user.getLong("total").longValue();
        map.put("total", total);
        arrts.add(map);
        return arrts;
    }

    public boolean ajaxUpdate(String privilegeID, String masterVal, String accessName, String accessVal) {

        Role role = Role.dao.findFirst("select * from role where roleValue = ? ", masterVal);
        String masterName = role.getStr("roleName");
        boolean result = Privilege.dao.findById(privilegeID).set("masterName", masterName).set("masterVal", masterVal)
                .set("accessName", accessName).set("accessVal",accessVal).update();

        return result;
    }

    public boolean ajaxDel(String privilegeID) {
        return Privilege.dao.deleteById(privilegeID);
    }
}
